<template>
  <!-- 新增部门的弹层 -->
  <el-dialog
    :title="isShowTitle"
    :visible="showDialog"
    @close="butSend"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      ref="deptForm"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item
        prop="name"
        label="部门名称"
      >
        <el-input
          v-model="formData.name"
          style="width:80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item
        prop="code"
        label="部门编码"
      >
        <el-input
          v-model="formData.code"
          style="width:80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门负责人"
        prop="manager"
      >
        <el-select
          v-model="formData.manager"
          style="width:80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="部门介绍"
        prop="introduce"
      >
        <el-input
          v-model="formData.introduce"
          style="width:80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row
      slot="footer"
      type="flex"
      justify="center"
    >
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click="butOK"
        >确定</el-button>
        <el-button
          size="small"
          @click="butSend"
        >取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: '',
  components: {},
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    const checkNameRepeat = async(rules, value, callback) => {
      let isRepeat = false
      /* 获取最新的数据列表 */
      const { depts } = await getDepartments()

      if (this.formData.id) {
        /* 如果存在则是编辑 */
        isRepeat = depts
          .filter(
            (item) =>
              item.pid === this.treeNode.pid && item.id !== this.treeNode.id
          )
          .some((item) => item.name === value)
      } else {
        /* 否则是新增 */

        /* 判断当前字段是否存在与父节点的子节点里 */
        isRepeat = depts
          .filter((item) => item.pid === this.treeNode.id)
          .some((item) => item.name === value)
      }

      isRepeat
        ? callback(new Error(`同级部门下已存在${value},请重新命名 !`))
        : callback()
    }
    const checkCodeRepeat = async(rules, value, callback) => {
      let isRepeat = false

      /* 获取最新的数据列表 */
      const { depts } = await getDepartments()

      if (this.formData.id) {
        /* 如果存在则是编辑 */
        isRepeat = depts
          .filter((item) => item.id !== this.treeNode.id)
          .some((item) => item.code === value)
      } else {
        /* 否则是新增 */

        /* 判断所有的部门编码是否存在重复 */
        isRepeat = depts.some((item) => item.code === value)
      }

      isRepeat ? callback(new Error(`部门编码重复 !`)) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            validator: checkNameRepeat
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            validator: checkCodeRepeat
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      },
      peoples: []
    }
  },
  computed: {
    isShowTitle() {
      return this.formData.id ? '编辑部门' : '添加子部门'
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async getEmployeeSimple() {
      /* 获取员工信息 */
      this.peoples = await getEmployeeSimple()
    },
    butOK() {
      this.$refs.deptForm.validate(async(isOk) => {
        if (isOk) {
          if (this.formData.id) {
            /* 编辑部门 */
            await updateDepartments(this.formData)
          } else {
            /* 添加部门 */
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
          }

          /* 成功提示 */
          this.$message.success('操作成功! ')

          /* 重新获取数据,回显页面 */
          this.$emit('addDepts')

          /* 使用sync修饰符,直接修改父组件里的数据 */
          this.$emit('update:showDialog', false)
        }
      })
    },
    butSend() {
      /* 初始化标题数据的判断条件 */
      this.formData = { name: '', code: '', manager: '', introduce: '' }

      /* 关闭弹窗 */
      this.$emit('update:showDialog', false)
      /* 初始化校验 */
      this.$refs.deptForm.resetFields()
    },
    /* 获取当前部门的详细信息 */
    async getDepartDetail(id) {
      /* 将详细信息通过双向绑定回显到表单里 */
      /* 抛出问题: props属性获取数据是异步的,所以我们不能在同步任务中使用props里的数据,所以,我们在父组件里调用该方法. */
      this.formData = await getDepartDetail(id)
    }
  }
}
</script>
<style scoped lang='less'></style>
